import { formatToHump } from './utils.js'
import fs from 'fs'
import { Db } from './database.js'
export const createRouter = (tableName, tableDesc) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    const humpTableName = formatToHump(tableName)
    const folder = `${config.vendorFolder}/${humpTableName}`
    // verify file is exist or not
    const fileName = `${folder}/router.ts`
    if (fs.existsSync(fileName)) {
      // file is exist
      console.log(`======file is exist and ignore to created router:${tableName}=======`)
    } else {
      // file is not exist
      if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      const routerArr = getRouterTemplate(config, tableName, tableDesc)
      const content = `export const router = ${routerArr}`
      fs.writeFile(fileName, content, { flag: 'a' }, (err) => {
        if (err) {
          console.log('========error======')
          throw err
        } else {
          console.log(`======succeessfully created router:${tableName}=======`)
        }
      })
      // register routers
      registeRouters(routerArr)
      return routerArr
    }
  })
}
const getRouterTemplate = (config, tableName, tableDesc) => {
  const folder = config.view.folder.replace(/src\//, '')
  const humpTableName = formatToHump(tableName)
  return `[
  {
    path: '/${tableName}/list',
    name: '${formatToHump(tableName + '_list')}',
    meta: {
      title: '${tableDesc}列表'
    },
    component: () => import('@/${folder}/${humpTableName}/list.vue')
  },
  {
    path: '/${tableName}/detail',
    name: '${formatToHump(tableName + '_detail')}',
    meta: {
      title: '${tableDesc}详情'
    },
    component: () => import('@/${folder}/${humpTableName}/detail.vue')
  },
  {
    path: '/${tableName}/add',
    name: '${formatToHump(tableName + '_add')}',
    meta: {
      title: '${tableDesc}添加'
    },
    component: () => import('@/${folder}/${humpTableName}/add.vue')
  },
  {
    path: '/${tableName}/update',
    name: '${formatToHump(tableName + '_update')}',
    meta: {
      title: '${tableDesc}修改'
    },
    component: () => import('@/${folder}/${humpTableName}/update.vue')
  }
]`
}
export const appendTopRouter = (tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    const humpTableName = formatToHump(tableName)
    // verify file is exist or not
    const routerFile = `./${humpTableName}/router`
    const fileName = `${config.vendorFolder}/topRouter.ts`
    const routerName = formatToHump(`router_${tableName}`)
    const importContent = `import { router as ${routerName} } from '${routerFile}'\n`
    if (fs.existsSync(fileName)) {
    // read as object and update file
      fs.readFile(fileName, 'utf8', (err, data) => {
        if (err) throw err
        if (data.indexOf(importContent) === -1) {
          const content = importContent + data + `.concat(${routerName})`
          writeStoreRouter(fileName, content)
        }
      })
    } else {
    // file is not exist
      if (!fs.existsSync(`${config.vendorFolder}`)) {
        fs.mkdirSync(`${config.vendorFolder}`, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      const content = `${importContent}export const topRouter = ${routerName}`
      writeStoreRouter(fileName, content, 'a')
    }
  })
}
export const writeStoreRouter = (fileName, content, flag = 'w') => {
  fs.writeFile(fileName, content, { flag }, (err) => {
    if (err) {
      console.log('========error======')
      throw err
    } else {
      console.log('======succeessfully append top router =======')
    }
  })
}

// 路由表同步
export const syncRouter = (routersStr) => {

}

const getRoutersArr = (routersStr) => {
  const routers = []
  let pathResult = null
  let nameResult = null
  let titleResult = null
  const pathPattern = /path:\s*'(.*?)',/g
  const namePattern = /name:\s*'(.*?)',/g
  const titlePattern = /title:\s*'(.*?)'\s+}/g
  do {
    pathResult = pathPattern.exec(routersStr)
    nameResult = namePattern.exec(routersStr)
    titleResult = titlePattern.exec(routersStr)
    if (pathResult && nameResult && titleResult) {
      routers.push({
        path: pathResult[1],
        name: nameResult[1],
        title: titleResult[1]
      })
    }
  } while (pathResult && nameResult && titleResult)
  return routers
}

/**
 * 路由注册入数据库
 * @param {array} routers router array
 */
export const registeRouters = (routersStr) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    // const pattern = /.*?path:(.*?),.*?name:(.*?),.*?title:(.*?)/g

    const db = new Db(config.systemDb.host, config.systemDb.user, config.systemDb.password, config.systemDb.database, config.systemDb.port)
    const routers = getRoutersArr(routersStr)

    const dataArr = []
    const promises = []
    const tableName = config.systemDb.tablePrefix + config.systemDb.tables.registerRouter
    routers.forEach((router) => {
      const search = { name: router.name }
      db.clean()
      const promise = db.where(search).select(tableName)
        .then((rows) => {
          if (rows === undefined || rows.length === 0) {
            dataArr.push({
              pid: 0,
              status: 1,
              is_menu: 2,
              icon: '',
              app: config.systemDb.appName,
              name: router.name,
              title: router.title,
              path: router.path
            })
          }
        })
      promises.push(promise)
    })
    Promise.all(promises).then(() => {
      if (dataArr.length === 0) {
        console.log('============no menu insert data=========')
        db.end()
      } else {
        db.inserts(tableName, dataArr).then(() => { }).catch(() => {
          throw err('insert routers error')
        }).finally(() => { db.end() })
      }
    })
  })
}
